package com.luo.Filter;

import com.alibaba.fastjson.JSON;
import com.luo.model.ResultObj;
import com.luo.util.RedisUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/1/5 20:07
 */
@WebFilter(urlPatterns = "/*")
public class RespSetFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        //请求编码设置
        resp.setCharacterEncoding("utf8");
        resp.setContentType("text/http;charset=utf8");
        req.setCharacterEncoding("utf8");

        //跨域设置
        // 允许所有来源
        resp.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的方法
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        // 允许的头部信息
        // resp.setHeader("Access-Control-Allow-Headers", "Authorization,Content-Type");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        // 允许跨域请求包含cookies
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        //token校验
        String authorization = req.getHeader("authorization");
        String index = "Bearer ";
        if (authorization != null){
            try {
                authorization = authorization.substring(authorization.lastIndexOf(index) + index.length());
                // 拿到token进行判断该token是否过期
                // 连接到Redis
                Jedis jedis = RedisUtil.getJedis();
                String fieldValue = jedis.hget(authorization, "token");
                String username = jedis.hget(authorization, "currentTime");
                String id = jedis.hget(authorization,"id");
                if (id == null){
                    // 说明token过期了
                    ResultObj resultObj = new ResultObj();
                    resultObj.setCode("-3");
                    resultObj.setMsg("token已过期");
                    String jsonString = JSON.toJSONString(resultObj);
                    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    resp.getWriter().write(jsonString);
                    resp.getWriter().close();
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("出现了异常token");
            }
        }

        //放行
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
